<template>
  <div
    :class="unStatus === false ? 'tzy-selected-pop' : 'tzy-selected-popTabs'"
  >
    <div class="tzy-selected-pop__left" @click="unfoldChange">
      <div class="tzy-selected-pop__left-info">
        <el-icon
          v-if="unStatus === false"
          color="#fff"
          style="margin-left: 14px"
        >
          <DArrowLeft />
        </el-icon>
        <el-icon v-else color="#fff" style="margin-left: 14px">
          <DArrowRight />
        </el-icon>
        <div class="tzy-selected-pop__text">志愿表</div>
        <div class="tzy-selected-pop__num">{{ volunteerInfos.length }}</div>
      </div>
      <div class="uzy-button save" @click.stop="onClickSaveVolunteer">保存</div>
      <div class="uzy-button save" @click.stop="onClickTop">顶部</div>
    </div>
    <div class="tzy-selected-pop__content-right">
      <el-input
        v-model="searchKey"
        style="max-width: 600px"
        placeholder=""
        class="height40"
        @keyup.enter="handleEnter"
        @input="searchInputChange"
      >
        <template #append>
          <el-button type="primary" @click="handleEnter">搜索</el-button>
        </template>
      </el-input>
      <el-scrollbar ref="listRef" class="tzy-content-list margintop">
        <VueDraggable
          ref="el"
          v-model="volunteerInfos"
          :animation="150"
          ghostClass="ghost"
          class="flex-col gap-2 p-4 w-300px h-300px m-auto bg-gray-500/5 rounded"
          @end="draggableEnd"
        >
          <div
            class="tzy-contetn-list-date"
            v-for="(data, index) in volunteerInfos"
            :key="data.id"
          >
            <div class="between">
              <div
                class="left"
                style="width: 86%; display: flex; flex-direction: row"
              >
                <div
                  class="tzy-content-number"
                  :class="
                    data.chance_lv == 1
                      ? 'chance1'
                      : data.chance_lv == 2
                        ? 'chance2'
                        : 'chance3'
                  "
                >
                  {{ index + 1 }}
                </div>
                <div
                  class="tzy-content-name"
                  v-html="searchHandle(data.collegeRealName)"
                ></div>
              </div>

              <el-icon size="16" class="curr">
                <Rank />
              </el-icon>
              <el-popconfirm
                confirm-button-text="删除"
                cancel-button-text="取消"
                icon-color="#626AEF"
                title="确认删除"
                @confirm="onClickDeleteCollege(index)"
              >
                <template #reference>
                  <el-icon class="curr" size="16">
                    <Delete />
                  </el-icon>
                </template>
              </el-popconfirm>
            </div>
            <div
              class="between margintop"
              v-for="(major, idx) in data.majorsInfo"
              :key="idx"
            >
              <div>
                <span class="sizeName">{{ idx + 1 }}</span>
                <div
                  class="tzy-contetn-name"
                  v-html="searchHandle(major.professionName)"
                ></div>
              </div>
              <el-icon
                size="18"
                color="#ccc"
                class="curr"
                @click="onClickDeleteMajor(index, idx)"
              >
                <Close />
              </el-icon>
            </div>
          </div>
        </VueDraggable>
      </el-scrollbar>
      <el-button
        type="primary"
        class="height40"
        style="width: 100%; background-color: #165dff"
        @click="onClickSaveVolunteer"
        >保存志愿表（{{ Object.keys(volunteerInfos).length }}）</el-button
      >
    </div>
  </div>
</template>
<script setup>
import { VueDraggable } from 'vue-draggable-plus';

import { ref } from 'vue';
import volunteersStore from '@/store/modules/volunteerInfos';
import { zySave } from '/src/api/appv2/appv2.js';
import { ElMessage } from 'element-plus';
import { useRouter } from 'vue-router';

const emit = defineEmits(['onClickTop']);

const router = useRouter();
const volunteerStore = volunteersStore();

const volunteerInfos = ref([]);
const storeVolunteerInfos = computed(() => volunteerStore.volunteerInfos);

const { id: teacherId, groupId } = JSON.parse(
  localStorage.getItem('userDateInfo')
);

const listRef = ref(null);
const unStatus = ref(false);
const searchKey = ref(''); // 搜索字段

const props = defineProps({
  studentData: {
    type: Object,
    default: {},
  },
  batchInfo: {
    type: Object,
    default: {},
  },
});

watch(
  storeVolunteerInfos,
  (newVal) => {
    volunteerInfos.value = newVal;
  },
  { immediate: true }
);

// 拖拽排序结束
function draggableEnd(event) {
  if (event.oldIndex != event.newIndex) {
    volunteerStore.setVolunteerInfos(volunteerInfos.value);
  }
}

function unfoldChange() {
  unStatus.value = !unStatus.value;
}

function searchInputChange() {
  currentIndex.value = 0;
  setTimeout(() => {
    handleEnter();
  }, 100);
}

let currentIndex = ref(0);
const validElements = ref([]);
// 有时候DOM会多出来一个offsetTop为0的元素  这里过滤掉这个为0的元素 否则会有问题
const handleEnter = () => {
  validElements.value = document.querySelectorAll('.spanHighlight');
  if (validElements.value.length > 0) {
    validElements.value = Array.from(validElements.value).filter(
      (element) => element.offsetTop !== 0
    );
    if (validElements.value.length > 0) {
      currentIndex.value = currentIndex.value % validElements.value.length;
      if (currentIndex.value > 0) {
        validElements.value[currentIndex.value - 1].classList.remove(
          'highlightBackGround'
        ); // 移除前一个高亮元素的背景色
      } else {
        validElements.value[validElements.value.length - 1].classList.remove(
          'highlightBackGround'
        ); // 移除最后一个高亮元素的背景色
      }
      const targetElement = validElements.value[currentIndex.value];
      targetElement.classList.add('highlightBackGround'); // 添加背景颜色

      listRef.value.scrollTo({
        top: targetElement.offsetTop,
        behavior: 'smooth',
      });

      currentIndex.value++; // 更新索引，准备下次跳转
    }
  }
};

// 搜索关键字修改颜色
function searchHandle(val) {
  let text = val; // 初始状态下设为普通文本

  if (searchKey.value) {
    var reg = new RegExp('(' + searchKey.value + ')', 'g');
    text = val.replace(reg, (match) => {
      return `<span ref="spanRef"  id="spanHighlight" class="spanHighlight" style='color:#165dff ;font-weight:bolder'>${match}</span>`;
    });
  }
  return text;
}

// 点击删除填报的院校
function onClickDeleteCollege(index) {
  volunteerInfos.value.splice(index, 1);
  volunteerStore.setVolunteerInfos(volunteerInfos.value);
}

/**
 * 点击删除填报的院校专业
 * @param Number index 志愿表中院校下标
 * @param Number majorIdx 院校下专业下标
 */
function onClickDeleteMajor(index, majorIdx) {
  volunteerInfos.value[index].majorsInfo.splice(majorIdx, 1);

  // 判断填报院校下专业是否被全部删除，是则删除该院校
  if (volunteerInfos.value[index].majorsInfo.length == 0) {
    volunteerInfos.value.splice(index, 1);
  }
  volunteerStore.setVolunteerInfos(volunteerInfos.value);
}

// 点击保存志愿表
function onClickSaveVolunteer() {
  let volunteerInfo = volunteerInfos.value;
  console.log('volunteerInfo:', volunteerInfo);

  if (volunteerInfo.length < 3) {
    ElMessage({
      message: '至少填报三个院校',
      type: 'warning',
    });
    return;
  }

  let rate = 0;
  for (let volunteer of volunteerInfo) {
    rate = rate + Number(volunteer.chance);
  }
  rate = (rate / volunteerInfo.length).toFixed(0);
  rate = rate + '%';

  let studentInfo = props.studentData.student;

  let data = {};
  data['studentId'] = props.studentData.studentId;
  console.log(studentInfo, '保存famiy', props.batchInfo);

  let str = '';

  if (props.batchInfo.score) {
    data['course'] = localStorage.getItem('course') || undefined;
    data['score'] = props.batchInfo.score;
    data['sgname'] = props.batchInfo.sgname;
    data['section'] = props.batchInfo.section;
    data['copyfrom'] = props.batchInfo.copyfrom;
    str = `${props.batchInfo.score}分${props.batchInfo.section}位${props.batchInfo.sgname}|${props.batchInfo.batch}`;
  } else {
    data['course'] = localStorage.getItem('courseNew') || undefined;

    data['score'] = studentInfo.score;
    data['sgname'] = studentInfo.sgname;
    data['section'] = studentInfo.section;
    str = `${studentInfo.score}分${studentInfo.section}位${studentInfo.sgname}|${studentInfo.batch}`;
  }
  data['family'] = str;
  
  // data['batch'] = props.batchInfo.batch;
  data['batch'] = localStorage.getItem('zhigao') == 1 ? '高职单招' : '中职单招';
  data['createFrom'] = 1;

  data['zy_type'] = 2;
  data['isTeacherSee'] = 1;
  data['isStudentSee'] = 0;
  console.log(volunteerInfo, '保存出错');

  data['volunteerInfos'] = JSON.stringify(volunteerInfo);
  data['rate'] = rate;
  data['teacherId'] = teacherId;
  data['groupId'] = groupId;
  data['is_danzhao'] = localStorage.getItem('zhigao') || 1;

  // return;
  zySave(data).then((ref) => {
    volunteerStore.setVolunteerInfos([]);

    let body = JSON.stringify({
      index: ref.data.index,
      zy_type: 2,
      studentData: props.studentData,
    });
    body = btoa(encodeURIComponent(body));
    router.push({
      path: '/leader/savevolunteerd',
      query: {
        data: body,
      },
    });
  });
}

// 点击回到顶部
function onClickTop() {
  emit('onClickTop');
}

defineExpose({
  unfoldChange,
});
</script>
<style lang="scss" scoped>
.ghost {
  opacity: 0.5;
  background: #c8ebfb;
}

.tzy-selected-popTabs {
  right: 10px;
  position: fixed;
  top: 64px;
  width: 400px;
  height: 200px;
  z-index: 2000;
  transform: translateX(0px);
  transition: transform 0.6s;
  display: flex;

  .tzy-selected-pop__content-right {
    flex: 1;
    background: #fff;
    border-radius: 0 0 0 4px;
    padding: 20px;
    overflow: hidden;
    box-shadow: -10px 0 10px 0 rgba(0, 0, 0, 0.05);
    height: calc(100vh - 100px);
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: space-between;

    .tzy-content-list {
      flex: 1;
      width: 100%;
      overflow-x: hidden;
      overflow-y: auto;
      ::v-deep .el-scrollbar__thumb {
        background-color: #333333 !important;
      }

      .tzy-contetn-list-date {
        background: #f7f8fa;
        border-radius: 4px 4px 4px 4px;
        padding: 12px 16px;
        margin-bottom: 10px;

        .tzy-contetn-name {
          display: inline-block;
          padding-right: 10px;
          font-size: 14px;
          font-weight: 400;
          color: #4e5969;
          line-height: 20px;
        }

        .sizeName {
          font-size: 14px;
          font-weight: 400;
          padding-right: 10px;
          color: #212121;
        }

        .tzy-content-number {
          text-align: center;
          // background-color: #F53F3F;
          color: #ffffff;
          min-width: 23px;
          height: 22px;
          line-height: 22px;
          border-radius: 4px;
        }

        .tzy-content-name {
          margin-left: 12px;
        }
      }
    }
  }

  .tzy-selected-pop__left {
    width: 48px;
    height: 246px;
    cursor: pointer;
    position: absolute;
    left: -48px;
    top: 106px;

    .uzy-button {
      width: 48px;
      height: 42px;
      font-size: 16px;
      font-weight: 400;
      line-height: 42px;
      background-color: #ffffff;
      text-align: center;
      color: #165dff;
      border: 1px solid #165dff;
    }

    .tzy-selected-pop__left-info {
      padding-top: 16px;
      border: 1px solid transparent;
      border-right: none;
      border-top-left-radius: 4px;
      background: #165dff;

      .tzy-selected-pop__text {
        width: 16px;
        height: 66px;
        font-size: 16px;
        font-weight: 400;
        color: #fff;
        margin: 0 auto;
        line-height: 22px;
        margin-bottom: 8px;
      }

      .tzy-selected-pop__num {
        text-align: center;
        font-size: 24px;
        font-family:
          PingFang SC-Semibold,
          PingFang SC;
        font-weight: 600;
        color: #fff;
        line-height: 24px;
        margin-bottom: 16px;
      }
    }
  }
}

.tzy-selected-pop {
  right: 10px;
  position: fixed;
  top: 64px;
  width: 400px;
  height: 200px;
  z-index: 2000;
  transform: translateX(400px);
  transition: transform 0.6s;
  display: flex;

  .tzy-selected-pop__content-right {
    flex: 1;
    background: #fff;
    border-radius: 0 0 0 4px;
    padding: 20px;
    overflow: hidden;

    .tzy-content-list {
      flex: 1;
      width: 100%;
      overflow-x: hidden;
      overflow-y: auto;
      ::v-deep .el-scrollbar__thumb {
        background-color: #333333 !important;
      }

      .tzy-contetn-list-date {
        background: #f7f8fa;
        border-radius: 4px 4px 4px 4px;
        padding: 12px 16px;
        margin-bottom: 10px;

        .tzy-contetn-name {
          display: inline-block;
          padding-right: 10px;
          font-size: 14px;
          font-weight: 400;
          color: #4e5969;
          line-height: 20px;

          .sizeName {
            color: #212121;
          }
        }

        .tzy-content-number {
          text-align: center;
          background-color: #f53f3f;
          color: #ffffff;
          width: 23px;
          height: 22px;
          line-height: 22px;
          border-radius: 4px;
        }

        .tzy-content-name {
          margin-left: 12px;
        }
      }
    }
  }

  .tzy-selected-pop__left {
    width: 48px;
    height: 246px;
    cursor: pointer;
    position: absolute;
    left: -48px;
    top: 106px;

    .uzy-button {
      width: 48px;
      height: 42px;
      font-size: 16px;
      font-weight: 400;
      line-height: 42px;
      background-color: #ffffff;
      text-align: center;
      color: #165dff;
      border: 1px solid #165dff;
    }

    .tzy-selected-pop__left-info {
      padding-top: 16px;
      border: 1px solid transparent;
      border-right: none;
      border-top-left-radius: 4px;
      background: #165dff;

      .tzy-selected-pop__text {
        width: 16px;
        height: 66px;
        font-size: 16px;
        font-weight: 400;
        color: #fff;
        margin: 0 auto;
        line-height: 22px;
        margin-bottom: 8px;
      }

      .tzy-selected-pop__num {
        text-align: center;
        font-size: 24px;
        font-family:
          PingFang SC-Semibold,
          PingFang SC;
        font-weight: 600;
        color: #fff;
        line-height: 24px;
        margin-bottom: 16px;
      }
    }
  }
}

.chance1 {
  background-color: #f53f3f;
}

.chance2 {
  background-color: #ff8c33;
}

.chance3 {
  background-color: #00bf10;
}
</style>

<style>
.highlightBackGround {
  background: #165dff;
  color: #fff !important;
}
</style>
